import os
import requests
import re
import io
import sys
from PIL import Image
from openpyxl import Workbook
from openpyxl.drawing.image import Image as OpenpyxlImage
from openpyxl.utils import get_column_letter
from config_manager import get_config

# --- 配置 ---
# GITLAB_URL = os.getenv('GITLAB_URL', 'http://10.28.120.90')
# PRIVATE_TOKEN = os.getenv('GITLAB_PRIVATE_TOKEN')
# ASSIGNEE_USERNAME = 'meihaohui'
# OUTPUT_FILE = f'gitlab_issues_with_images_{ASSIGNEE_USERNAME}.xlsx'

# --- 图像显示配置 ---
IMAGE_WIDTH = 200  # 嵌入图片的固定宽度（像素）

# headers = { 'PRIVATE-TOKEN': PRIVATE_TOKEN }

def fetch_all_issues(gitlab_url, headers, assignee_username):
    # (此函数与原脚本相同，此处省略以保持简洁)
    """
    通过分页获取所有相关的问题
    """
    issues = []
    page = 1
    while True:
        params = {
            'assignee_username': assignee_username,
            'scope': 'all',
            'per_page': 100,
            'page': page
        }
        print(f"正在获取第 {page} 页的所有问题...")
        try:
            response = requests.get(f"{gitlab_url}/api/v4/issues", headers=headers, params=params, verify=False)
            response.raise_for_status()
            data = response.json()
            if not data:
                break
            issues.extend(data)
            page += 1
        except requests.exceptions.RequestException as e:
            print(f"请求API时发生错误: {e}")
            if e.response is not None and e.response.status_code == 401:
                print("错误：认证失败 (401)。请检查你的 GITLAB_PRIVATE_TOKEN。")
            return None
    return issues

def main():
    try:
        config = get_config()
    except Exception as e:
        print(f"加载配置时出错: {e}")
        sys.exit(1)

    GITLAB_URL = config['url']
    PRIVATE_TOKEN = config['token']
    ASSIGNEE_USERNAME = config['username']
    
    headers = { 'PRIVATE-TOKEN': PRIVATE_TOKEN }
    OUTPUT_FILE = f'gitlab_issues_with_images_{ASSIGNEE_USERNAME}.xlsx'


    all_issues = fetch_all_issues(GITLAB_URL, headers, ASSIGNEE_USERNAME)
    if all_issues is None:
        print("获取问题失败，脚本终止。")
        return
    
    # 在内存中筛选出 'opened' 状态的 issue
    opened_issues = [issue for issue in all_issues if issue.get('state') == 'opened']

    print(f"已获取全部 {len(all_issues)} 条 issue，筛选后剩下 {len(opened_issues)} 条 'opened' 状态的 issue。")

    if not opened_issues:
        print("没有找到 'opened' 状态的问题。")
        return

    print(f"总共找到 {len(opened_issues)} 个问题。开始处理并下载图片...")

    # --- 使用 openpyxl 创建工作簿 ---
    wb = Workbook()
    ws = wb.active
    ws.title = "GitLab Issues"

    # --- 定义并写入表头 ---
    columns = ['ID', 'IID', 'Project ID', 'Title', 'Description', 'Picture', 'State', 'Created At', 'Updated At', 'Closed At', 'Author', 'Assignee', 'Labels', 'Web URL']
    ws.append(columns)

    # --- 设置列宽 ---
    # (可根据需要调整)
    column_widths = {'A': 10, 'B': 10, 'C': 15, 'D': 40, 'E': 50, 'F': 30, 'G': 10, 'H': 20, 'I': 20, 'J': 20, 'K': 15, 'L': 15, 'M': 40, 'N': 60}
    for col_letter, width in column_widths.items():
        if col_letter <= get_column_letter(len(columns)):
             ws.column_dimensions[col_letter].width = width

    # --- 循环处理每个 issue ---
    for i, issue in enumerate(opened_issues):
        print(f"正在处理第 {i+1}/{len(opened_issues)} 个 issue: {issue['title'][:30]}...")
        
        # 提取基础信息
        author = issue['author']['username'] if issue.get('author') else 'N/A'
        assignee = issue['assignee']['username'] if issue.get('assignee') else 'N/A'
        description_raw = issue.get('description') or ''
        web_url = issue.get('web_url', '')

        # 提取图片链接
        picture_urls = []
        if '/-/issues/' in web_url:
            project_url = web_url.split('/-/issues/')[0]
            relative_paths = re.findall(r"!\[.*?\]\((/uploads/[^)]+)\)", description_raw)
            for path in relative_paths:
                picture_urls.append(f"{project_url}{path}")
        
        description_cleaned = re.sub(r"\!\[.*?\]\(/uploads/[^)]+\)\s*", "", description_raw).strip()

        # --- 准备写入行的数据 ---
        base_row_data = [
            issue.get('id'), issue.get('iid'), issue.get('project_id'), issue.get('title'),
            description_cleaned, '', issue.get('state'), issue.get('created_at'),
            issue.get('updated_at'), issue.get('closed_at'), author, assignee,
            ', '.join(issue.get('labels', [])), web_url
        ]

        # --- 如果没有图片 ---
        if not picture_urls:
            ws.append(base_row_data)
            continue
        
        # --- 如果有图片，为每张图片创建一行 ---
        for img_index, img_url in enumerate(picture_urls):
            current_row_data = base_row_data[:] # 复制基础数据
            
            # 如果是第一张图之后的行，清空非关键信息避免重复感
            if img_index > 0:
                for idx_to_clear in [0,1,2,3,4,6,7,8,9,10,11,12,13]: # 清空除图片外的所有列
                    current_row_data[idx_to_clear] = ''

            ws.append(current_row_data)
            current_row_num = ws.max_row

            try:
                print(f"  -> 正在下载图片: {img_url[-50:]}")
                response = requests.get(img_url, headers=headers, verify=False, timeout=10)
                response.raise_for_status()
                
                img_data = io.BytesIO(response.content)
                img = Image.open(img_data)

                # 计算新尺寸，保持宽高比
                aspect_ratio = img.height / img.width
                new_height = int(IMAGE_WIDTH * aspect_ratio)
                
                # 设置行高 (points)
                ws.row_dimensions[current_row_num].height = new_height * 0.75 # px to pt conversion

                # 创建 openpyxl 图片对象
                ooxml_img = OpenpyxlImage(img)
                ooxml_img.width = IMAGE_WIDTH
                ooxml_img.height = new_height
                
                # 'F' 是 Picture 列
                ws.add_image(ooxml_img, f'F{current_row_num}')

            except Exception as e:
                print(f"  -> [警告] 无法下载或处理图片 {img_url}: {e}")
                ws.cell(row=current_row_num, column=6).value = f"图片加载失败: {img_url}"
    
    # --- 保存文件 ---
    try:
        print("正在保存 Excel 文件...")
        wb.save(OUTPUT_FILE)
        print(f"\n成功！包含图片的问题已导出到文件: {os.path.abspath(OUTPUT_FILE)}")
    except Exception as e:
        print(f"导出到Excel时发生错误: {e}")

if __name__ == "__main__":
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    main() 